

// Mason D. HILL
// Assignment #6
// Video Link:  https://www.youtube.com/watch?v=NOmlXSRZvN8




#define F_CPU 8000000UL // 8 mhz

#include <util/delay.h> // delay library
#include <avr/io.h> // input/output library
#include <avr/interrupt.h>//interrupt library


int outputadded = 0; // Holds the analog read value


int softstop = 0; // Soft timer delay for servo
int steppervalue = 1; // Which stepper position for stepper motor.
int softstopstepper = 0; // Soft timer delay for stepper

ISR(TIMER2_OVF_vect){
	/// TIMER2 is used as the control for the stepper.

softstopstepper++; // Increment the counter

int delayfrompot = outputadded/10;  // To make the stepper faster or slower, a variable delay is needed. 
if(softstopstepper>delayfrompot){ // Checking if the delay has been passed and can turn a tick.

softstopstepper=0; // Set value to 0 as execution happened
		PORTD = (steppervalue); // Update the output to the stepper
		
		
		
		steppervalue*=2; /// Go to the next stepper state
		if(steppervalue==16) steppervalue = 1; // Stepper reached its final state. Need to go back to 0.
		
}		



}

ISR(TIMER0_OVF_vect){
	/// TIMER0 is used as the control for the servo.

	

	softstop++; // Increment the counter
	if(softstop==10){ // Check if the delay has passed.
		softstop=0;// Set value to 0 as execution happened
		OCR1A=500 + 1.8*  outputadded;// The output value of the duty cycle for OCR1A was experimentally found to be from approximately 500 to 2350.
		}
		

}







void adc_init(){
	
	ADCSRA = 0b11100111; // Initialize the ADC.
	ADCSRB = 0b00000000; // Make sure the register is clear
	DIDR0 = 0b00111110; // oNLY READING FROM ADC0
	
}









int main(void)
{
DDRB = 0b11111111; // B acts as the seg select for the 8 seg.
	DDRD = 0xFF; /// DDRD is an output



adc_init(); // Initialize the adc



TCCR0A = 0b00000000;// Make sure it is 0 initially
TCCR0B = 0b00000101; 	// cs is 101 (prescalar 1024)


TCCR2A = 0b00000000;// Make sure it is 0 initially
TCCR2B = 0b00000110; 	// cs is 110 (prescalar 256)


EICRA = 0b00000010; // Sets the interrupt for falling edge.
TIMSK0 = 1; // Enables the overflow interrupt for timer 0.
TIMSK2 = 1; // Enables the overflow interrupt for timer 2.
sei(); // Enable the interrupt

	ICR1 = 20000; // Sets the frequency and with CS generates: 8,000,000/(20000*8(prescalar))=50 hz.
	TCCR1A|=(0<<COM1A0)|(1<<COM1A1)|(0<<COM1B0)|(0<<COM1B1)|(0<<FOC1A)|(0<<FOC1B)|(1<<WGM11)|(0<<WGM10); // Set for PWM,
	TCCR1B|=(0<<ICNC1)|(0<<ICES1)|(1<<WGM13)|(1<<WGM12)|(0<<CS12)|(1<<CS11)|(0<<CS10); // Set for prescalar 8.
	


while(1)
{
	


	
	outputadded = ADCH *256 + ADCL; // ADCH holds the upper two bits of the analog, ADCL holds the lower 8 bits of the analog. outputadded contains the sum of the two.



	
}


return 0;
}
